
import operator
import sys

goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998}
]

user_dict = dict()
user_buy_list = list()
user_buy_current_list = list()
with open('user.txt', 'r', encoding='utf-8') as user_file:
    user_list = user_file.read().split(' ')
    user_dict[user_list[0]] = [user_list[1], user_list[2]]

with open('user_buy.txt', 'r', encoding='utf-8') as user_buy_file:
    lines = user_buy_file.readlines()
    for line in lines:
        good_dict = dict()
        good = line.split(' ')
        good_dict['name'] = good[0]
        good_dict['price'] = good[1]
        user_buy_list.append(good_dict)


def validate_user(username, password):
    if username not in user_dict:
        return False
    else:
        if operator.eq(password, user_dict[username][0]):
            return True
        else:
            return False


def print_goods(goods):
    for index, value in enumerate(goods):
        print('%d. 货物:%s 价格:%s ' % (index + 1, value['name'], value['price']))


def exit_save_to_file(salary):
    with open('user.txt', 'w', encoding='utf-8') as user_file:
        user_file.write('aaaa' + ' ' + 'aaaa' + ' ' + salary)
    with open('user_buy.txt', 'a', encoding='utf-8') as user_buy_file:
        for dict in user_buy_current_list:
            user_buy_file.writelines(dict['name'] + ' ' + dict['price'])


def print_highlight(message):
    print('\033[1;31m %s !\033[00m' % (message))

# print('This is a \033[1m test \033[0m !')
# print('\033[1;31m This is a test !')


# 登录
login_user = ''
login_user_salary = 0
while True:
    username = input('enter your username: ')
    password = input('enter your password: ')
    if validate_user(username, password):
        login_user = username
        login_user_salary = float(user_dict[username][1])
        break

# 输入工资
if login_user_salary < 0:
    salary = float(input('enter your salary: '))
    login_user_salary = salary

print_highlight('your salary is %f' % login_user_salary)

while True:
    print_goods(goods)

    sel_good_num = input('q is quit, h is histroy buy,enter a num:')

    if operator.eq(sel_good_num, 'q'):
        print_goods(user_buy_current_list)
        print_highlight('your salary is %f' % login_user_salary)
        exit_save_to_file(login_user_salary)
        sys.exit(0)
    elif operator.eq(sel_good_num, 'h'):
        print_goods(user_buy_list)
        print('-------------------')
        continue

    sel_good_num = int(sel_good_num)
    if sel_good_num > 0:
        good_dict = goods[sel_good_num - 1]
        good_price = int(good_dict['price'])
        if good_price > login_user_salary:
            print_highlight('salary is not enough')
        else:
            login_user_salary -= good_price
            user_buy_current_list.append(good_dict)
            print_highlight('pay complete!')
    else:
        print_highlight('enter num is illegal')
